source code: Validate uploaded file extension

Category > ASP.NET || Published on : Tuesday, September 8, 2020 || Views: 646 || Validate uploaded file extension


Here Pawan Kumar will explain how to Validate uploaded file extension

<asp:RegularExpressionValidator 
     ID="regexValidateImageFil" runat="server" ControlToValidate="fuImage" 
     ErrorMessage="file type not allow." 
     ValidationExpression="^([0-9a-zA-Z_\-~ :\\])+(.jpg|.JPG|.jpeg|.JPEG|.bmp|.BMP|.gif|.GIF|.png|.PNG)$"></asp:RegularExpressionValidator>

bool CheckFileType(string fileName)
{
    string ext = Path.GetExtension(fileName);
    switch (ext.ToLower())
    {
        case ".gif":
            return true;
        case ".jpg":
            return true;
        case ".jpeg":
            return true;
        case ".png":
            return true;
        default:
            return false;
    }
}

if (CheckFileType(fuImage.FileName))
{
 //..........
}